package com.zhongkai.web.tag;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.log4j.Logger;

import com.zhongkai.dao.TagDao;
import com.zhongkai.model.config.Sequence;
import com.zhongkai.tools.SpringUtils;

public class SequenceTag extends TagSupport {
	
	Logger log = Logger.getLogger(this.getClass());

	private String key=null;

	@Override
	public int doStartTag() throws JspException {
		try {
			if(key==null || key.matches(""))
				throw new RuntimeException("请输入序列key!");
			TagDao tagDao=(TagDao)SpringUtils.getBean("tagDao",this.pageContext.getServletContext());
			Sequence sequence=(Sequence)tagDao.selectById(Sequence.class, key);
			if(sequence==null)
				throw new RuntimeException("该序列不存在!");
			sequence.setSequenceValue(sequence.getSequenceValue()+1);
			tagDao.update(sequence);
			JspWriter writer = pageContext.getOut();
			writer.println(sequence.getSequenceValue());
		} catch (Exception ex) {
			try {
				ex.printStackTrace();
				String path=((HttpServletRequest)pageContext.getRequest()).getContextPath();
				log.error(ex.getMessage());
				((HttpServletResponse) pageContext.getResponse())
						.sendRedirect(path+"/errorpage.jsp?errorinfo="
								+ java.net.URLEncoder.encode(ex.toString(),
										"UTF-8"));
			} catch (java.io.IOException ioe) {
				log.error(ioe.getMessage());
			}
		}
		return SKIP_BODY;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}
}
